#!/usr/bin/env python
#coding=utf-8

from __future__ import division
import time
import sys
from define import BASE_DIR
sys.path.append(BASE_DIR)

from lib.abstract_cron import abstract_cron
from lib.func_ext import dateTypeInterval,str2sec,sec2str,ksort

#需要修改
class business_report_day(abstract_cron) :

    #需要修改
    #noLock = True   #是否生成脚本锁文件
    #selectTable = 'sdb_statistics_api_hour'
    insertTable = 'sdb_statistics_business_report'

    def __init__(self) :
        #需要修改
        super(business_report_day,self).__init__(__file__)

    def boot(self,timestamp=[]) :
#        self.preBoot()

        bizData = self.getBizData(timestamp)
        orderData = self.getOrderData(timestamp)

        if bizData and orderData :
            #获取订单表中有 而商家表中 没有的节点信息
            bizNodes = set(bizData.keys())
            orderNodes = set(orderData.keys())
            diffNodes = orderNodes-bizNodes

            #先计算商家的数据 Note:以商家数据还是订单为基础都可以(这里使用商家数据为基础)
            for k,v in bizData.iteritems() :
                # 此处 k(即node_id)必定存在 在获取的时候已经过滤
                nodeOrder = orderData.get(k,{})
                if nodeOrder :
                    #nodeOrder['amounts'] = 0    #商品数目统计 目前没有 数据库默认为0
                    v.update(nodeOrder)
                else :
                    self.processNoOrder(v)
                
                api_sum = v.get('api_sum') and int(v.get('api_sum')) or 0
                api_sum_succ = v.get('sum_succ') and int(v.get('sum_succ')) or 0
                v['api_failnum'] = api_sum - api_sum_succ

                #计算成功率
                self.figureRatio(v,'api_sum','api_failnum','apisuccrate')
                #数据过滤
                self.filterItems(v)

            #计算订单中有 而商家中没有的节点数据
            if diffNodes :
                for node in diffNodes :
                    var = orderData.get(node,{})
                    self.processNoBiz(var)
                    #数据过滤
                    self.filterItems(var)
        elif bizData :
            for k,v in bizData.iteritems() :
                self.processNoOrder(v,True)
                #数据过滤
                self.filterItems(v)
        elif orderData :
            for k,v in orderData.iteritems() :
                self.processNoBiz(v)
                #数据过滤
                self.filterItems(v)

        #批量插入
        self.doBatchExec()

        self.sufBoot()
        print 'ok'


    def processNoOrder(self,biz,filterValue=False) :
        """""""""""""""""""""""""""""""""""""""
         # 对只有商家信息没有订单信息的处理
         #
         # @author   alone <phperlon@gmail.com>
         # @param    dict biz 商家信息字典对象
         # @param    bool filterValue 对值过滤
         # @return   void
         # @todo     
        """""""""""""""""""""""""""""""""""""""
        biz['num'] = 0
        biz['amount_money'] = 0.0
        #biz['amounts'] = 0     #商品数目统计 目前没有 数据库默认为0
        if filterValue :
            api_sum = biz.get('api_sum') and int(biz.get('api_sum')) or 0
            api_sum_succ = biz.get('sum_succ') and int(biz.get('sum_succ')) or 0
            biz['api_failnum'] = api_sum - api_sum_succ

            #计算成功率 过滤成功率>1和失败次数<0的情况
            self.figureRatio(biz,'api_sum','api_failnum','apisuccrate')

    def processNoBiz(self,order) :
        """""""""""""""""""""""""""""""""""""""
         # 对只有订单信息没有商家信息的处理
         #
         # @author   alone <phperlon@gmail.com>
         # @param    dict biz 商家信息字典对象
         # @param    bool filterValue 对值过滤
         # @return   void
         # @todo     
        """""""""""""""""""""""""""""""""""""""
        order['api_sum'] = 0
        order['api_failnum'] = 0
        order['apisuccrate'] = 1.0

    def getBizData(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql = 'SELECT `node_id`,`node_type`,`sum` AS api_sum,`sum_succ`,`date`,`call_time` AS calltime'
        sql += ' FROM sdb_statistics_business_day WHERE '+self.db._filter(timeFilter)
        row = self.db.select(sql)
        if row :
            self.writeSql(sql,'succ','select')
            bizData = {}
            for v in row :
                node_id = v.get('node_id')
                if node_id :
                    bizData[str(int(node_id))] = v
            return bizData
        else :
            self.writeSql(sql,'fail','select')

    def getOrderData(self,timestamp=[]) :
        timeFilter = self.getTimeFilter(timestamp)
        sql = 'SELECT `node_id`,`node_type`,`num`,`price` AS amount_money,`date`,`calltime`'
        sql += ' FROM sdb_statistics_order_day WHERE '+self.db._filter(timeFilter)
        row = self.db.select(sql)
        if row :
            self.writeSql(sql,'succ','select')
            orderData = {}
            for v in row :
                node_id = v.get('node_id')
                if node_id :
                    orderData[str(int(node_id))] = v
            return orderData
        else :
            self.writeSql(sql,'fail','select')

    def getTimeFilter(self,timestamp=[]) :
        keyFilter = {}
        keyFilter['date'] = timestamp and timestamp or (int(sec2str('%Y%m%d',time.time()-1*24*3600)))
        return keyFilter

    def insertKeys(self) :
        return ['node_id','node_type','api_sum','api_failnum','apisuccrate','num','amount_money','amounts','date','calltime']


#需要修改
if __name__ == '__main__' :
    obj = business_report_day()
    obj.boot()
    #obj.boot(20110314)
